package zxing.activity;

import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dispatchapp.andlei.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import adapter.CaptureAdapter;
import base.BaseBean;
import base.activity.BaseLayoutActivity;
import bean.DetailBean;
import netWork.NetUtils;
import ui.activity.homepage.DispatchRiderActivity;
import utils.GsonUtils;
import utils.Logger;
import utils.SPUtils;
import widget.HiDialog;
import zxing.MessageIDs;
import zxing.camera.CameraManager;
import zxing.decoding.CaptureActivityHandler;
import zxing.decoding.InactivityTimer;
import zxing.view.ViewfinderView;

///**
// * Initial the camera
// * @author Ryan.Tang
// */
//public class CaptureActivity extends Activity implements Callback {

/**
 * Initial the camera
 * 扫描二维码界面
 */
public class CaptureActivity extends BaseLayoutActivity implements Callback {
    public static final String QR_RESULT = "RESULT";

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private SurfaceView surfaceView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    // private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    CameraManager cameraManager;
    private boolean isOpen;
    private RecyclerView recyclerView;
    private Button btn_complete;
    private CaptureAdapter adapter;
    private List<DetailBean> list = new ArrayList<>();
    private NetUtils netUtils;
    private int addr_id;
    private int mCameraID = 0;
//    /**
//     * Called when the mActivity is first created.
//     */
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        //super.onCreate(savedInstanceState);
//
////		requestWindowFeature(Window.FEATURE_NO_TITLE);
//        setTitle("扫一扫");
//        surfaceView = (SurfaceView) findViewById(R.id.preview_view);
//        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
//
//        Window window = getWindow();
//        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//
//        hasSurface = false;
//        inactivityTimer = new InactivityTimer(this);
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("扫描取餐");
        setTitlefontBg_black();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        // CameraManager.init(getApplication());
        cameraManager = new CameraManager(getApplication());
        viewfinderView.setCameraManager(cameraManager);

        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        cameraManager.closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_capture;
    }

    @Override
    protected void findViews() {
        netUtils = new NetUtils(mActivity, netRequestCallBack);
        surfaceView = getView(R.id.preview_view);
        viewfinderView = getView(R.id.viewfinder_view);
        getView(R.id.tv_shanguang).setOnClickListener(this);
        recyclerView = getView(R.id.list_rcy);
        btn_complete = getView(R.id.btn_complete);
        btn_complete.setOnClickListener(this);
        if (SPUtils.getInstance(mActivity).getString("Is_coach").equals("2")) {
            btn_complete.setText("分配骑手");
        }
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
//        for (int i =0;i<20;i++){
//            TestBean bean = new TestBean();
//            bean.str = i+"号楼";
//            list.add(bean);
//        }
    }

    @Override
    protected void formatViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CaptureAdapter(R.layout.item_capter, list);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                if (view.getId() == R.id.img_delete) {
                    new HiDialog.Builder(CaptureActivity.this)
                            .setContent("是否确认删除？")
                            .setLeftBtnText("否")
                            .setRightBtnText("是")
                            .setRightCallBack(new HiDialog.RightClickCallBack() {
                                @Override
                                public void dialogRightBtnClick() {
                                    adapter.remove(position);
                                    adapter.notifyDataSetChanged();
                                }
                            }).build();
                }
            }
        });
    }

    @Override
    protected void formatData() {

    }

    @Override
    protected void getBundle(Bundle bundle) {

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            cameraManager.openDriver(surfaceHolder);
        } catch (IOException | RuntimeException ioe) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    public void handleDecode(Result obj, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        handlerScanResult(obj);
//		showResult(obj, barcode);
    }

    @NonNull
    private void handlerScanResult(Result rawResult) {
        String resultString = rawResult.getText();
        toast("扫描结果："+resultString);
        Map<String, Object> map = new HashMap<>();
        map.put("order_no", "" + resultString);
        netUtils.get("rider/user/detail", map, BaseBean.class, null, false);
        Logger.i("toast", "resultString = " + resultString);

    }

//    private void showDialog() {
//        //扫描失败，是否重试
//        final android.app.AlertDialog myDialog = new android.app.AlertDialog.Builder(ScanCodeActivity.this).create();
//
//        myDialog.show();
//        myDialog.getWindow().setContentView(R.layout.dialog_scan_tip);
//        myDialog.getWindow().findViewById(R.id.tv_login_ok)
//                .setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        restartPreviewAfterDelay(0L);
//                        myDialog.dismiss();
//                    }
//                });
//
//        myDialog.getWindow().findViewById(R.id.tv_login_cancel)
//                .setOnClickListener(new View.OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        myDialog.dismiss();
//                        finish();
//                    }
//                });
//    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(MessageIDs.restart_preview, delayMS);
        }
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            try {
                AssetFileDescriptor fileDescriptor = getAssets().openFd("qrbeep.ogg");
                this.mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                        fileDescriptor.getLength());
                this.mediaPlayer.setVolume(0.1F, 0.1F);
                this.mediaPlayer.prepare();
            } catch (IOException e) {
                this.mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_CANCELED);
            finish();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_shanguang:
                lightOn();
                break;
            case R.id.btn_complete:
                String order_nos = "";
                int j = 0;
                for (DetailBean bean : list) {
                    j++;
                    order_nos += bean.getOrder_no() + ",";
                }
                if (TextUtils.isEmpty(order_nos)) {
                    return;
                }
                order_nos = order_nos.substring(0, order_nos.length() - 1);
                if (SPUtils.getInstance(mActivity).getString("Is_coach").equals("2")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("order_no", order_nos);
                    bundle.putString("addr_id", addr_id + "");
                    bundle.putString("order_num", j + "");
                    bundle.putString("homepage", "true");
                    jumpTo(DispatchRiderActivity.class, bundle);
                    finish();
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("order_nos", "" + order_nos);
                    netUtils.post("rider/user/sweep-order", map, BaseBean.class, false);
                }
                break;
        }
    }

    /**
     * 闪光灯控制，CaptureActivity里面
     */
    private void lightOn() {
        if (!isOpen) {
            cameraManager.openFlashLight();
            isOpen = true;
        } else {  // 关灯
            cameraManager.offFlashLight();
            isOpen = false;
        }
//        cameraManager.closeDriver();
//        if(mCameraID == 0){
//            mCameraID =1;
//        }else {
//            mCameraID =0;
//        }
//        SurfaceHolder surfaceHolder = surfaceView.getHolder();
//        initCamera(surfaceHolder);
    }

    private NetUtils.NetRequestCallBack netRequestCallBack = new NetUtils.NetRequestCallBack() {
        @Override
        public void error(String action, Throwable e, Map tag) {
            restartPreviewAfterDelay(0L);
        }

        @Override
        public void success(String action, BaseBean t, Map tag) {
            if (t.getCode() == 200) {
                switch (action) {
                    case "rider/user/detail":
                        DetailBean detailBean = (DetailBean) GsonUtils.getInstance(mActivity).parseComplexJArrayByCommon(t, DetailBean.class);
                        boolean have = false;
                        for (DetailBean bean : list) {
                            if (bean.getOrder_no().equals(detailBean.getOrder_no())) {
                                have = true;
                            }
                        }
                        if (!have) {
                            if (list.size() > 0) {
                                addr_id = list.get(0).getAddr_id();
                                if (SPUtils.getInstance(mActivity).getString("Is_coach").equals("2")) {
                                    if (addr_id == detailBean.getAddr_id()) {
                                        list.add(detailBean);
                                    } else {
                                        toast("不是同一学校订单，请扫描同一学校订单");
                                    }
                                } else {
                                    list.add(detailBean);
                                }
                            } else {
                                addr_id = detailBean.getAddr_id();
                                list.add(detailBean);
                            }
                            adapter.notifyDataSetChanged();
                        }
                        break;
                    case "rider/user/sweep-order":
                        if (t.getCode() == 200) {
                            setResult(100);
                            finish();
                        } else {
                            toast(t.getMsg());
                        }
                        break;
                }
            } else {
                toast(t.getMsg());
            }
            restartPreviewAfterDelay(0L);
        }
    };
}